package com.chatmusicstatus.service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.os.IBinder;
import com.chatmusicstatus.MainActivity;
import com.chatmusicstatus.R;
import com.chatmusicstatus.accounts.AccountSQLiteHelper;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.jivesoftware.smack.XMPPException;

public class MusicStatusService extends Service{
    
    private MusicStatusReceiver mReceiver;
    private AccountSQLiteHelper accHelper;
    
    //Code taken from com.example.android.apis.app to implement foreground service
    public static final String ACTION_FOREGROUND = "com.chatmusicstatus.service.FOREGROUND";
    public static final String ACTION_BACKGROUND = "com.chatmusicstatus.service.BACKGROUND";
    
    private static final Class<?>[] mSetForegroundSignature = new Class[] {
        boolean.class};
    private static final Class<?>[] mStartForegroundSignature = new Class[] {
        int.class, Notification.class};
    private static final Class<?>[] mStopForegroundSignature = new Class[] {
        boolean.class};
    
    private NotificationManager mNM;
    private Method mSetForeground;
    private Method mStartForeground;
    private Method mStopForeground;
    private Object[] mSetForegroundArgs = new Object[1];
    private Object[] mStartForegroundArgs = new Object[2];
    private Object[] mStopForegroundArgs = new Object[1];
    
    void invokeMethod(Method method, Object[] args) {
        try {
            method.invoke(this, args);
        } catch (InvocationTargetException e) {
            // Should not happen.
        } catch (IllegalAccessException e) {
            // Should not happen.
        }
    }
    void startForegroundCompat(int id, Notification notification) {
        if (mStartForeground != null) {
            mStartForegroundArgs[0] = Integer.valueOf(id);
            mStartForegroundArgs[1] = notification;
            invokeMethod(mStartForeground, mStartForegroundArgs);
            return;
        }
        
        mSetForegroundArgs[0] = Boolean.TRUE;
        invokeMethod(mSetForeground, mSetForegroundArgs);
        mNM.notify(id, notification);
    }
    void stopForegroundCompat(int id) {
        if (mStopForeground != null) {
            mStopForegroundArgs[0] = Boolean.TRUE;
            invokeMethod(mStopForeground, mStopForegroundArgs);
            return;
        }

        mNM.cancel(id);
        mSetForegroundArgs[0] = Boolean.FALSE;
        invokeMethod(mSetForeground, mSetForegroundArgs);
    }


    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    
    @Override   
    public void onCreate() {
        //Stop the music so that the service can maintain the state
        mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        try {
            mStartForeground = getClass().getMethod("startForeground",
                    mStartForegroundSignature);
            mStopForeground = getClass().getMethod("stopForeground",
                    mStopForegroundSignature);
        } catch (NoSuchMethodException e1) {
            // Running on an older platform.
            mStartForeground = mStopForeground = null;
        
            try {
                mSetForeground = getClass().getMethod("setForeground",
                        mSetForegroundSignature);
            } catch (NoSuchMethodException e2) {
                throw new IllegalStateException(
                        "OS doesn't have Service.startForeground OR Service.setForeground!");
            }
        }
        
        stopMusic();
        IntentFilter iF = new IntentFilter();
        iF.addAction("com.android.music.metachanged");
        iF.addAction("com.android.music.playstatechanged");
        iF.addAction("com.android.music.playbackcomplete");
        //iF.addAction("com.android.music.queuechanged");
        accHelper = new AccountSQLiteHelper(this);
        Cursor c=accHelper.getActiveAccounts();;
        try {
            mReceiver = new MusicStatusReceiver(c,this);
            registerReceiver(mReceiver, iF);
        } catch (XMPPException ex) {
            c.close();
        }
    }
    @Override
    public void onStart(Intent intent, int startId) {
        handleCommand(intent);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //Toast.makeText(this, "Service onStartCommand", Toast.LENGTH_SHORT).show();
        handleCommand(intent);
        return START_STICKY;
    }
    void handleCommand(Intent intent) {
        if (ACTION_FOREGROUND.equals(intent.getAction())) {
            CharSequence text = getText(R.string.foreground_service_started);

            Notification notification = new Notification(R.drawable.ic_stat_xmpp_music, text,
                    0);

            PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                    new Intent(this, MainActivity.class), 0);

            notification.setLatestEventInfo(this, getText(R.string.local_service_label),
                           text, contentIntent);

            startForegroundCompat(R.string.foreground_service_started, notification);

        } else if (ACTION_BACKGROUND.equals(intent.getAction())) {
            stopForegroundCompat(R.string.foreground_service_started);
        }
    }

    @Override
    public void onDestroy() {
        if(mReceiver!=null)
            mReceiver.stopReceive();
        stopForegroundCompat(R.string.foreground_service_started);
        //Toast.makeText(this, R.string.serviceStopMsg, Toast.LENGTH_SHORT).show();
    }
    
    private void stopMusic() {
        Intent musicIntent = new Intent();
        musicIntent.setAction("com.android.music.musicservicecommand");
        musicIntent.putExtra("command", "stop"); // or "next" or "previous"
        sendBroadcast(musicIntent);
    }
    
}
